#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Project:     src-server
# @File:        prj_info_serv.py
# @Author:      Fan GuiChuan
# @Date:        2025/10/14 16:40
# @Version:     Python3.7
# @Description:
import datetime

from flask import request
from app.models.models import db, PrjInfo


class PrjInfoServ:
    def __init__(self, logger):
        self.logger = logger

    def add_prj(self):
        try:
            prj_data = request.json
            self.logger.debug(f"add prj: {prj_data}")
            prj_name = (prj_data.get('prj_name') or '').strip()
            if not prj_name:
                return False, '项目名不能为空。'

            # 检查是否存在项目名称
            existing = PrjInfo.query.filter_by(prj_name=prj_name).first()
            if existing:
                return False, '项目名称已存在，请选择其他项目名称。'

            current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            new_prj = PrjInfo(prj_name=prj_name,
                              last_work_time=current_time,
                              update_time=current_time,
                              create_time=current_time)
            db.session.add(new_prj)
            db.session.commit()
            return True, new_prj.prj_id
        except Exception as e:
            self.logger.exception(str(e))

    def get_prj_list(self):
        """
        获取项目列表信息
        """
        try:
            req_data = request.json
            labels = PrjInfo.query.order_by(PrjInfo.last_work_time.desc()).all()
            result = []
            for label in labels:
                result.append(label.to_dict())
            return True, result
        except Exception as e:
            self.logger.exception(str(e))
            return False, str(e)
